<?php
/**
 * Author: yann
 * QQ: 9197313
 * Date: 2018/11/27 0027
 * Time: 下午 4:19
 */

namespace app\api\controller;
use app\model\Attach;
use app\model\Lottery as _Lottery;
use app\model\LotteryAttend;
use app\model\LotteryCode;
use app\model\LotteryFormid;
use app\model\LotteryLog;
use app\model\MpFans;
use app\util\ReturnCode;
use think\Db;
use think\Queue;

class Lottery extends Base
{
    public function index(){
//        $token = $this->request->header('Authorization');
//        return $this->buildSuccess($token);
        $page = $this->request->post('page',1);
        $size = $this->request->post('size',10);
        $result = (new _Lottery())->getList([['status','=',1],['end_time','>',time()]],$page,$size);
        $return = [
            'list' => $result['list'],
            'paging' => $this->buildPaging($result['count'],$page,$size),
            'winners_lists' => (new LotteryAttend())->getWinners()
        ];
        return $this->buildSuccess($return);
    }

    public function info(){
        $id = $this->request->post('id',0);
        $attend = $this->request->post('attend',0);
        if(!$id)
            return $this->buildFailed(ReturnCode::EMPTY_PARAMS,'参数错误');

        //分享给好友，好友点击增加一个抽奖码
        if($attend){
            (new LotteryCode())->assistCode($attend, session('openid'), $id);
        }
        $attend_id = LotteryAttend::where(['lid'=>$id,'openid'=>session('openid')])->value('id');
        $return = [
            'attend_id' => $attend_id ? $attend_id : 0,
            'info' => (new _Lottery())->getInfo($id,session('openid'))
        ];
        return $this->buildSuccess($return);
    }

    public function attend(){
        $lid = $this->request->post('lid');
        $openid = session('openid');
        $form_id = $this->request->post('formid');
        if((new MpFans())->checkInfo($openid)){

            $ex = LotteryAttend::where(['lid'=>$lid,'openid'=>$openid])->count();
            if(!$ex){
                $data = [
                    'lid' => $lid,
                    'form_id' => $form_id,
                    'openid' => $openid
                ];
                $res = (new LotteryAttend())->attend($data,$openid,$lid);

                if($res != false){
                    $return = $res;
                    $return['info'] = (new _Lottery())->getInfo($lid,session('openid'));
                    return $this->buildSuccess($return,'参与成功');
                }else{
                    return $this->buildSuccess([],'已经参与');
                }
            }else{
                return $this->buildSuccess([],'已经参与');
            }

        }else{
            return $this->buildFailed(ReturnCode::INVALID,'用户信息不完整');
        }
    }

    public function getAttend(){
        $lid = $this->request->post('lid',0);
        if(!$lid)
            return $this->buildFailed(ReturnCode::EMPTY_PARAMS,'参数错误');
        $page = $this->request->post('page',1);
        $size = $this->request->post('size',20);

        $order = 'lottery_code_count desc';
        $data = [
            'lid' => $lid,
            'openid' => session('openid')
        ];
        $result = (new LotteryAttend())->getList($data,$page,$size,$order);
        $attend_id = LotteryAttend::where($data)->value('id');
        $return = [
            'list' => $result['list'],
            'paging' => $this->buildPaging($result['count'],$page,$size),
            'attend_id' => $attend_id ? $attend_id : 0
        ];
        return $this->buildSuccess($return);
    }

    public function center(){
        $openid = session('openid');
        $return = [
            'attend' => LotteryAttend::where(['openid'=>$openid])->count(),
            'lottery' => _lottery::where(['openid'=>$openid])->count(),
            'open' => LotteryLog::where(['openid'=>$openid])->count(),
            'settings' => []
        ];
        return $this->buildSuccess($return);
    }

    public function myattend(){
        $page = $this->request->post('page',1);
        $size = $this->request->post('size',20);
        $openid = session('openid');
        $result = (new LotteryAttend())->getMyAttend($openid,$page,$size);
        $return = [
            'list' => $result['list'],
            'paging' => $this->buildPaging($result['count'],$page,$size),
            'settings' => []
        ];
        return $this->buildSuccess($return);
    }

    public function mylottery(){
        $page = $this->request->post('page',1);
        $size = $this->request->post('size',20);
        $openid = session('openid');
        $result = (new _Lottery())->getList(['openid'=>$openid],$page,$size);
        $return = [
            'list' => $result['list'],
            'paging' => $this->buildPaging($result['count'],$page,$size),
            'settings' => []
        ];
        return $this->buildSuccess($return);
    }

    public function myopen(){
        $page = $this->request->post('page',1);
        $size = $this->request->post('size',20);
        $openid = session('openid');
        $result = (new LotteryLog())->getMyOpen($openid,$page,$size);
        $return = [
            'list' => $result['list'],
            'paging' => $this->buildPaging($result['count'],$page,$size),
            'settings' => []
        ];
        return $this->buildSuccess($return);
    }

    public function settings(){
        return $this->buildSuccess([]);
    }

    public function canvas(){
        $lid = $this->request->post('lid');
        $t = $this->request->post('t');
        $attend_id = 0;
        if($t != 2){
            $attend_id = LotteryAttend::where(['lid'=>$lid,'openid'=>session('openid')])->value('id');
        }

        if($attend_id!=0){
            $path = '/pages/info/main?id='.$lid.'&attend_id='.$attend_id;
            $xcxcode = $this->getwxaqrcode($path,$lid,$attend_id);

        }else{
            $path = '/pages/info/main?id='.$lid;
            $xcxcode = $this->getwxaqrcode($path,$lid);
        }
        try{
            $data = _Lottery::where(['id'=>$lid])->field('id,openid,title,pic,content,end_time,prize_num')->find();
            $data['end_time'] = date('m月d日 H:i',$data['end_time']);
            $data['xcxcode'] = $xcxcode;
            if($data['openid'] != ''){
                $userInfo = MpFans::where(['openid'=>$data['openid']])->field('nickname,headimgurl')->find();
                $data['nickname'] = $userInfo['nickname'];
                $data['headimgurl'] = $userInfo['headimgurl'];
            }else{
                $data['nickname'] = '微抽奖';
                $data['headimgurl'] = $this->request->domain().'/static/logo.jpg';
            }
            $data['settings'] = [];

            return $this->buildSuccess($data);
        }catch (\Exception $e){
            return $this->buildFailed($e->getCode(),$e->getMessage());
        }
    }

    public function saveFormId(){
        $formId = $this->request->post('formid');
        $count = LotteryFormid::where(['openid'=>session('openid')])->count();
        if($count <= 50 && $formId){
            LotteryFormid::create(['formid' => $formId , 'openid' => session('openid'),'end_time'=>time() + 3600*165]);
        }
        return $this->buildSuccess([]);
    }

    public function address(){
        $lid = $this->request->post('lid');
        $openid = session('openid');
        $do = $this->request->post('do');
        if($do == 'save'){
            $data = [
                'name' => $this->request->post('name'),
                'phone' =>$this->request->post('phone'),
                'address' => $this->request->post('address'),
                'remark' =>$this->request->post('remark')
            ];
            LotteryLog::update($data,['lid'=>$lid,'openid'=>$openid]);
            return $this->buildSuccess(['lid'=>$lid]);
        }
        if($do == 'get'){
            try{
                $data = LotteryLog::where(['lid'=>$lid,'openid'=>session('openid')])->find();
                return $this->buildSuccess($data);
            }catch (\Exception $e){
                return $this->buildFailed($e->getCode(),$e->getMessage());
            }
        }
    }

    private function getwxaqrcode($path,$lid,$attend_id=0){
//        $app = Factory::miniProgram(config('wechat.mini_program.default'));
//        $response = $app->app_code->getQrCode($path);
//        if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
//            if (!is_dir('./xcxcode'))
//                mkdir('./xcxcode', 0755, true);
//            $name = './xcxcode/'.$this->appid.'_'.$lid.'_'.$attend_id.'.jpg';
//            try{
//                $filename = $response->saveAs('./xcxcode', $name);
//                return $this->request->domain().ltrim($filename,'.');
//            }catch (\Exception $e) {
//                return false;
//            }
//        }
        if (!is_dir('./xcxcode'))
            mkdir('./xcxcode', 0755, true);
        $name = './xcxcode/'.$this->appid.'_'.$lid.'_'.$attend_id.'.jpg';
        if(!file_exists($name)){
            $url = 'https://api.weixin.qq.com/wxa/getwxacode?access_token='.$this->getAccessToken();
            $width = 430;
            $data = '{"path":"'.$path.'","width":'.$width.'}';
            $return = $this->httpGet($url,$data);
            //将生成的小程序码存入相应文件夹下
            file_put_contents($name,$return);
        }
        return $this->request->domain().ltrim($name,'.');
    }

    public function create(){
        $file = $this->request->file('imgfile');
        $savePath = './uploads';
        if (!is_dir($savePath))
            mkdir($savePath, 0755, true);

        $info = $file->validate(['size'=>2097152,'ext'=>'jpg,jpeg,png,gif'])->move($savePath);
        if($info){
            $path = $savePath.'/'.str_replace('\\','/',$info->getSaveName());
            Db::startTrans();
            try{
                Attach::create([
                    'type' => 0,
                    'name' => $info->getFilename(),
                    'save_type' => Attach::LOCALTYPE,
                    'ext' => $info->getExtension(),
                    'size' => $info->getSize(),
                    'path' => $path,
                    'create_time' => time()
                ]);

                _Lottery::create([
                    'openid' => session('openid'),
                    'title' => $this->request->post('title'),
                    'pic' => $this->request->domain().ltrim($path,'.'),
                    'num' => $this->request->post('num'),
                    'start_time' => time(),
                    'end_time' => strtotime($this->request->post('date')),
                    'status' => 1,
                    'sort' => 1,
                    'type' => 2,
                    'content' => $this->request->post('content')
                ]);
                Db::commit();
                return $this->buildSuccess([]);
            }catch (\Exception $e){
                Db::rollback();
                unlink($path);
                return $this->buildFailed($e->getCode(),$e->getMessage());
            }

        }else{
            return $this->buildFailed(ReturnCode::ADD_FAILED,$file->getError());
        }
    }

    public function openLottery(){

        $curentTime = time();

        $list = _Lottery::where([['end_time','<=',$curentTime],['open_type','=',1],['status','=',1]])->select()->toArray();

        foreach ($list as $key => $value) {
            $totalCode = LotteryCode::field('code,attend_id')->where(['lid'=>$value['id']])->select()->toArray();
            $attends = LotteryAttend::where(['lid'=>$value['id']])->select();
            $totalAttend = count($attends);
            $openCodes =[];

            if($totalAttend <= $value['prize_num']){
                // 如果参与总数 少于等于奖品数  必中
                $openCodes = LotteryCode::distinct(true)
                                ->field('code,attend_id')
                                ->where(['lid'=>$value['id']])
                                ->select()
                                ->toArray();
            }else{
                // 是否指定中奖
                if($value['appoint']!=''){

                    $tempCodes = explode("\n",$value['appoint']);
                    $tempNum = count($tempCodes);
                    $num = $value['num'] - $tempNum;
                    if($num > 0){
                        $openCodes = LotteryCode::field('code,attend_id')
                            ->where([['lid','=',$value['id'],['code','in',$tempCodes]]])
                            ->select()
                            ->toArray();

                        while (count($openCodes) != $value['prize_num']) {
                            $k = array_rand($totalCode,1);
                            $res = true;
                            foreach ($openCodes as $kk => $vv) {
                                if($totalCode[$k]['code'] == $vv['code'] || $totalCode[$k]['attend_id'] == $vv['attend_id']){
                                    $res = false;
                                }
                            }
                            if($res){
                                $openCodes[] = $totalCode[$k];
                            }
                        }

                    }else{
                        $openCodes = LotteryCode::field('code,attend_id')
                            ->where([['lid','=',$value['id'],['code','in',$tempCodes]]])
                            ->limit($value['num'])
                            ->select()
                            ->toArray();
                    }

                }else{

                    while (count($openCodes) != $value['prize_num']) {
                        $k = array_rand($totalCode,1);
                        $res = true;
                        foreach ($openCodes as $kk => $vv) {
                            if($totalCode[$k]['code'] == $vv['code'] || $totalCode[$k]['attend_id'] == $vv['attend_id']){
                                $res = false;
                            }
                        }
                        if($res){
                            $openCodes[] = $totalCode[$k];
                        }
                    }
                }
            }
            _Lottery::update(['status'=>2],['id'=>$value['id']]);

            foreach ($openCodes as $kkk => $vvv) {
                $temp = LotteryAttend::field('openid')->where(['id'=>$vvv['attend_id']])->find();
                LotteryLog::create([
                    'lid' =>$value['id'],
                    'openid' => $temp['openid'],
                    'code' => $vvv['code']
                ]);
            }

        }
        $this->inQueue();
    }

    private function inQueue(){
        try {
            $lottery_list = _Lottery::field('id')->where(['status'=>2])->select()->toArray();
            $send_list =[];
            foreach ($lottery_list as $key => $value){
                $send_list[] = $value['id'];
            }

            if($send_list){
                $attends = Db::view('LotteryAttend', 'id,lid,openid,form_id')
                    ->view('Lottery', 'title', 'Lottery.id=LotteryAttend.lid')
                    ->where('LotteryAttend.lid', 'in', $send_list)->select();
                if($attends){
                    foreach ($attends as $k =>$v){
                        if($v['form_id'] != 'the formId is a mock one'){
                            Queue::push('app\api\job\Message', json_encode($v), 'Message');
                        }
                    }
                }
                _Lottery::where('id','in',$send_list)->data(['status'=>3])->update();
            }

        } catch (\Exception $e) {
            return $e->getMessage();
        }

    }

}
